package net.lanelife.casino.cms.web.interceptor;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lanelife.casino.caipiao.entity.Preference;
import net.lanelife.casino.caipiao.service.api.IPreferenceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.common.collect.Maps;

import freemarker.ext.beans.BeansWrapper;

public class CommonDataInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private IPreferenceService preferenceService;

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
		if (!request.getHeader(HttpHeaders.ACCEPT).contains("application/json")) {
			//系统配置
			List<Preference> preferences = preferenceService.findAll();
			Map<String, Object> preferenceMap = Maps.newHashMap();
			for (Preference preference : preferences) {
				if (preference.getType() == Preference.Type.CONFIG) {
					preferenceMap.put(preference.getCode(), preference.parseValue());
				}
			}
			request.setAttribute("preference", preferenceMap);
		}
		
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//上下文路径
		if (request.getAttribute("ctx") == null) {
			request.setAttribute("ctx", request.getContextPath());
		}
		request.setAttribute("enums", BeansWrapper.getDefaultInstance().getEnumModels());
		//当前用户
		/*Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) { //是否已验证过
			String username = (String) subject.getPrincipal();
			if (StringUtils.isNotBlank(username)) {
				request.setAttribute(CurrentUser.CURRENT_USER_ATTRIBUTE_NAME, userService.findByUsername(username));
			}
		}*/
		
		return super.preHandle(request, response, handler);
	}

	
	
	

}
